package router

import (
	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
	"zk3/api/client"
	"zk3/api/enit"
	"zk3/common/pkg"
	"zk3/common/proto/user"
)

func Reg(c *gin.Context) {
	var data enit.User
	if err := c.ShouldBind(&data); err != nil {
		c.JSON(500, gin.H{
			"code": 500,
			"msg":  "参数错误",
		})
		return
	}
	err := pkg.SendSms(data.Mobile, data.Code)
	if err != nil {
		c.JSON(500, gin.H{
			"code": 500,
			"msg":  "验证码错误",
		})
		return
	}
	_, err = client.Reg(c, &user.RegRequest{
		Mobile: data.Mobile,
		Code:   data.Code,
	})
	if err != nil {
		c.JSON(500, gin.H{
			"code": 500,
			"msg":  "用户注册失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "用户注册成功",
	})
}

func Login(c *gin.Context) {
	var data enit.User
	if err := c.ShouldBind(&data); err != nil {
		c.JSON(500, gin.H{
			"code": 500,
			"msg":  "参数错误",
		})
		return
	}
	err := pkg.SendSms(data.Mobile, data.Code)
	if err != nil {
		c.JSON(500, gin.H{
			"code": 500,
			"msg":  "验证码错误",
		})
		return
	}
	login, err := client.Login(c, &user.LoginRequest{
		Mobile: data.Mobile,
		Code:   data.Code,
	})
	if err != nil {
		c.JSON(500, gin.H{
			"code": 500,
			"msg":  "用户登录失败",
		})
		return
	}
	CustomClaims := pkg.CustomClaims{
		ID: uint(login.UserId),
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: 86400,
		},
	}
	token, err := pkg.NewJWT("2211a").CreateToken(CustomClaims)
	if err != nil {
		c.JSON(500, gin.H{
			"code": 500,
			"msg":  "token 失效",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "用户登录成功",
		"data": token,
	})
}

func List(c *gin.Context) {
	var data enit.User
	if err := c.ShouldBind(&data); err != nil {
		c.JSON(500, gin.H{
			"code": 500,
			"msg":  "参数错误",
		})
		return
	}
	list, err := client.List(c, &user.ListRequest{Mobile: data.Mobile})
	if err != nil {
		c.JSON(500, gin.H{
			"code": 500,
			"msg":  "用户首页展示失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "用户首页展示成功",
		"data": list,
	})
}

func UserWorkCreate(c *gin.Context) {
	var data enit.UserWork
	if err := c.ShouldBind(&data); err != nil {
		c.JSON(500, gin.H{
			"code": 500,
			"msg":  "参数错误",
		})
		return
	}
	create, err := client.UserWorkCreate(c, &user.UserWorkCreateRequest{
		Author:      data.Author,
		ReleaseTime: data.ReleaseTime,
	})
	if err != nil {
		c.JSON(500, gin.H{
			"code": 500,
			"msg":  "作品发布失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "作品发布成功",
		"data": create,
	})
}
